import os
import datetime
from member_manager import manage_member_usage_interaction
from billing_calculator import calculate_and_display_bill_interaction
from storage_manager import (
    load_billing_history_from_file,
    save_bill_to_file,
    load_member_data_from_file,
    save_member_data_to_file
)

def display_main_menu():
    """显示主菜单选项"""
    print("\n===== 宿舍水电费分摊器 =====")
    print("1. 录入/更新宿舍成员用量信息")
    print("2. 录入总水电费用")
    print("3. 计算并显示分摊账单")
    print("4. 查看历史账单")
    print("5. 退出程序")
    print("============================")

def main_loop():
    """主程序循环"""
    # 确保数据目录存在
    if not os.path.exists("data"):
        os.makedirs("data")
    
    # 加载成员数据
    member_list = load_member_data_from_file()
    if not member_list:
        print("首次使用，请设置宿舍成员信息")
        member_input = input("请输入宿舍成员姓名，以逗号分隔（例如：张三,李四,王五）：")
        member_list = [name.strip() for name in member_input.split(",") if name.strip()]
        save_member_data_to_file(member_list)
        print(f"已保存成员列表：{', '.join(member_list)}")
    
    # 初始化数据
    current_members_data = {name: {"electricity": 0, "water": 0} for name in member_list}
    total_electricity_cost = 0.0
    total_water_cost = 0.0
    
    while True:
        display_main_menu()
        choice = input("请选择功能（输入数字1-5）：").strip()
        
        if choice == "1":
            # 录入/更新成员用量
            current_members_data, member_list = manage_member_usage_interaction(
                current_members_data, member_list
            )
            
        elif choice == "2":
            # 录入总费用
            while True:
                try:
                    total_electricity_cost = float(input("请输入总电费金额（元）：").strip())
                    if total_electricity_cost < 0:
                        print("电费金额不能为负数，请重新输入")
                        continue
                    break
                except ValueError:
                    print("请输入有效的数字金额")
            
            while True:
                try:
                    total_water_cost = float(input("请输入总水费金额（元）：").strip())
                    if total_water_cost < 0:
                        print("水费金额不能为负数，请重新输入")
                        continue
                    break
                except ValueError:
                    print("请输入有效的数字金额")
            
            print(f"已录入：总电费 {total_electricity_cost} 元，总水费 {total_water_cost} 元")
            
        elif choice == "3":
            # 计算并显示账单
            if not current_members_data:
                print("请先录入成员用量信息")
                continue
                
            if total_electricity_cost == 0 and total_water_cost == 0:
                print("请先录入总水电费用")
                continue
                
            # 生成当前时间戳
            billing_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            bill_object = calculate_and_display_bill_interaction(
                current_members_data, total_electricity_cost, total_water_cost
            )
            
            # 添加时间戳
            bill_object["billing_date"] = billing_date
            
            # 询问是否保存
            save_choice = input("是否保存本次账单？(y/n)：").strip().lower()
            if save_choice == "y" or save_choice == "yes":
                save_bill_to_file(bill_object)
                print("账单已保存")
                
        elif choice == "4":
            # 查看历史账单
            view_historical_bills_interaction()
            
        elif choice == "5":
            # 退出程序
            print("感谢使用宿舍水电费分摊器，再见！")
            break
            
        else:
            print("无效的选择，请输入1-5之间的数字")

if __name__ == "__main__":
    main_loop()    